import json
from django.http import JsonResponse
from django.views.generic import View
from ..utils.literUtils import handle_serializer_error, emptyValue
from django.db.models import Q
from django.core.paginator import Paginator
from utils.encryptionAndDecryptionUtil import get_useraccount_from_request
from datetime import datetime
import traceback
import copy
from control.models.User import User
from ..serializers.publicationListSerializer import JournalListQuerySerializer, JournalListSerializer, ConferenceListQuerySerializer, ConferenceListSerializer, BookListQuerySerializer, BookListSerializer
from ..serializers.publicationInfoSerializer import PublicationCreateSerializer, JournalCreateSerializer, ConferenceCreateSerializer, BookCreateSerializer, PublicationInfoSerializer, JournalInfoSerializer, ConferenceInfoSerializer, BookInfoSerializer
from ..serializers.authorInfoSerializer import AuthorCreateSerializer
from ..models.Publications import Journal, Book, Conference
from ..models.GlobalTables import JournalPublicationCycleType, ConferenceMeetingCycleType, Language, KeywordType, InstitutionType, DepartmentType
from ..models.Keyword import Keyword
from ..serializers.keywordInfoSerializer import SubjectCreateSerializer
from ..serializers.instInfoSerializer import InstCreateSerializer
from ..serializers.departInfoSerializer import DepartCreateSerializer
from ..models import Publications
from ..models.Author import Author
from ..models.Institution import Institution
from ..models.Department import Department

class PublicationView(View):
    def get(self, request, publication_type):
        res = {"code": 400, "message": "", "data": None}
        try:
            data = request.GET
            
            query_serializer = None
            config_serializer = None
            if publication_type == "Journal":
                query_serializer = JournalListQuerySerializer
                config_serializer = JournalListSerializer
            elif publication_type == "Conference":
                query_serializer = ConferenceListQuerySerializer
                config_serializer = ConferenceListSerializer
            elif publication_type == "Book":
                query_serializer = BookListQuerySerializer
                config_serializer = BookListSerializer
            else:
                res["code"] = 500
                res["message"] = "出版物类型不存在"
                return JsonResponse(res)
            
            query_list_serializer = query_serializer(data=data)
            data_valid = query_list_serializer.is_valid()
            if not data_valid:
                res["code"] = 400
                res["message"] = "参数错误：" + \
                    handle_serializer_error(
                        errors=query_list_serializer.errors)
                return JsonResponse(res)
            data = query_list_serializer.validated_data
            
            target_class = getattr(Publications, publication_type)
            all_list = target_class.objects.all().order_by('-create_date')
            
            query = Q()
            if "name" in data and data["name"] != "":
                query &= Q(name__icontains=data["name"])
            if "zh_name" in data and data["zh_name"] != "":
                query &= Q(zh_name__icontains=data["zh_name"])
            if "abbreviation" in data and data["abbreviation"] != "":
                query &= Q(abbreviation__icontains=data["abbreviation"])
            if "website" in data and data["website"] != "":
                query &= Q(website__icontains=data["website"])
            if "description" in data and data["description"] != "":
                query &= Q(description__icontains=data["description"])
            # if "subjects" in data and data["subjects"] != "":
            #     query &= Q(subjects__icontains=data["subjects"])
            # if "institutions" in data and data["institutions"] != "":
            #     query &= Q(institutions__icontains=data["institutions"])
            # if "departments" in data and data["departments"] != "":
            #     query &= Q(departments__icontains=data["departments"])
                
            if "issn" in data and data["issn"] != "":
                query &= Q(issn__icontains=data["issn"])
            if "cas" in data and data["cas"] != "":
                query &= Q(cas__icontains=data["cas"])
            if "impact_factor" in data and data["impact_factor"] != "":
                query &= Q(impact_factor__icontains=data["impact_factor"])
            if "founding_datej" in data and data["founding_datej"] != "":
                query &= Q(founding_datej__icontains=data["founding_datej"])
            if "contact_emailj" in data and data["contact_emailj"] != "":
                query &= Q(contact_emailj__icontains=data["contact_emailj"])
            if 'publication_cycle' in data and len(data['publication_cycle']) != 0:
                publication_cycle_list = [x['[0]'] for x in data['publication_cycle']]
                query &= Q(publication_cycle_id__in=publication_cycle_list)
            if "founding_datec" in data and data["founding_datec"] != "":
                query &= Q(founding_datec__icontains=data["founding_datec"])
            if "contact_emailc" in data and data["contact_emailc"] != "":
                query &= Q(contact_emailc__icontains=data["contact_emailc"])
            if 'meeting_cycle' in data and len(data['meeting_cycle']) != 0:
                meeting_cycle_list = [x['[0]'] for x in data['meeting_cycle']]
                query &= Q(meeting_cycle_id__in=meeting_cycle_list)
            if "publish_date" in data and data["publish_date"] != "":
                query &= Q(publish_date__icontains=data["publish_date"])
            if "isbn" in data and data["isbn"] != "":
                query &= Q(isbn__icontains=data["isbn"])
            if "page_number" in data and data["page_number"] != "":
                query &= Q(page_number__icontains=data["page_number"])
            if 'language' in data and len(data['language']) != 0:
                lang_list = [x['[0]'] for x in data['language']]
                query &= Q(language_id__in=lang_list)

                
            order_list_combined = []
            prop_list = data.get('sort_prop', '').split(
                ',') if data.get('sort_prop') else []
            order_list = data.get('sort_order', '').split(
                ',') if data.get('sort_order') else []
            if len(prop_list) != len(order_list):
                res["code"] = 400
                res["message"] = "排序参数错误"
                return JsonResponse(res)
            for i in range(len(prop_list)):
                for prop, order in zip(prop_list, order_list):
                    if order.lower() == 'ascending':
                        order_list_combined.append(prop)
                    elif order.lower() == 'descending':
                        order_list_combined.append(f'-{prop}')
                        
            if len(query) != 0:
                all_list = all_list.filter(query)
                
            if 'subjects' in data and data['subjects'] != "":
                sl = data['subjects'].split(";")
                ktp = KeywordType.objects.filter(name="Subject")[0]
                subject_all = Keyword.objects.filter(kt=ktp)
                for sn in sl:
                    ss = sn.strip()
                    sa = subject_all.filter(Q(k__icontains=ss) | Q(v__icontains=ss))
                    tmp_all_list = set()
                    for sss in all_list.filter(subjects__in=sa).all():
                        tmp_all_list.add(sss.uuid)
                    all_list = all_list.filter(uuid__in=tmp_all_list)
            if 'institutions' in data and data['institutions'] != "":
                il = data['institutions'].split(";")
                for i in il:
                    ii = i.strip()
                    ti = Institution.objects.filter(Q(name__icontains=ii) | Q(zh_name__icontains=ii))
                    tmp_all_list = set()
                    for aaa in all_list.filter(institutions__in=ti).all():
                        tmp_all_list.add(aaa.uuid)
                    all_list = all_list.filter(uuid__in=tmp_all_list)
            if 'departments' in data and data['departments'] != "":
                dl = data['departments'].split(";")
                for dn in dl:
                    dd = dn.strip()
                    td= Department.objects.filter(Q(name__icontains=dd) | Q(zh_name__icontains=dd))
                    tmp_all_list = set()
                    for aaa in all_list.filter(departments__in=td).all():
                        tmp_all_list.add(aaa.uuid)
                    all_list = all_list.filter(uuid__in=tmp_all_list)
                
            if 'authors' in data and data['authors'] != "":
                al = data['authors'].split(";")
                for an in al:
                    aa = an.strip()
                    ta = Author.objects.filter(Q(name__icontains=aa) | Q(zh_name__icontains=aa))
                    tmp_all_list = set()
                    for lll in all_list.filter(authors__in=ta).all():
                        tmp_all_list.add(lll.uuid)
                    all_list = all_list.filter(uuid__in=tmp_all_list)
                
            if len(order_list_combined) != 0:
                all_list = all_list.order_by(*order_list_combined)
            total_count = all_list.count()
            res_data = {}
            if "page_size" in data:
                page_size = data["page_size"]
                current_page = data["current_page"]
                paginator = Paginator(all_list, page_size)
                if current_page > paginator.num_pages:
                    current_page = paginator.num_pages
                page_obj = paginator.get_page(current_page)
                res_data["current_page"] = current_page
                res_data["page_size"] = page_size
                res_data["total_count"] = total_count
                all_list_serializer = config_serializer(
                    page_obj, many=True)
                res_data["objects"] = all_list_serializer.data
                res["code"] = 200
                res["message"] = "查询成功"
                res["data"] = res_data
                return JsonResponse(res)
            res_data["total_count"] = total_count
            all_list_serializer = config_serializer(
                all_list, many=True)
            res_data["objects"] = all_list_serializer.data
            res["code"] = 200
            res["message"] = "查询成功"
            res["data"] = res_data
            return JsonResponse(res)
        except Exception as e:
            traceback.print_exc()
            res["code"] = 500
            res["message"] = "服务器错误：" + str(e)
        return JsonResponse(res)
    
    
    def post(self, request, publication_type):
        res = {"code": 400, "message": "", "data": None}
        try:
            user_name = get_useraccount_from_request(request=request)
            u = User.objects.filter(user_account=user_name)[0]
            # print(request.body)
            data = json.loads(request.body)
            
            subject_id_list = []
            for subject in data["subjects"]:
                if 'uuid' in subject:
                    subject_id_list.append(subject['uuid'])
                else:
                    subject_add_serializer = SubjectCreateSerializer(data=subject)
                    subject_data_valid = subject_add_serializer.is_valid()
                    if not subject_data_valid:
                        print(subject_add_serializer.errors)
                        subject_serial_errors = handle_serializer_error(
                            errors=subject_add_serializer.errors)
                        res["code"] = 400
                        res["message"] = "参数错误：\n" + subject_serial_errors
                        return JsonResponse(res)
                    subject_data = subject_add_serializer.validated_data
                    subject_data["creator"] = u
                    subject_data["last_editor"] = u
                    subject_data['kt'] = KeywordType.objects.filter(name='Subject')[0]
                    t = Keyword.objects.create(**subject_data)
                    subject_id_list.append(t.uuid)
                    
            inst_infos = []
            for inst in data["institutions"]:
                inst_infos.append(copy.deepcopy(inst))
                if not isinstance(inst.get("departments"), list):
                    inst["departments"] = []
            
            for dep in data["departments"]:
                for i,inst in enumerate(inst_infos):
                    if dep["institution"] == inst:
                        data["institutions"][i]["departments"].append(dep)
                        
            institution_id_list = []
            department_id_list = []
            for inst in data["institutions"]:
                dep_data_list = inst.pop('departments', [])
                i_uuid = None
                if "uuid" in inst:
                    i_uuid = inst["uuid"]
                    institution_id_list.append(i_uuid)
                else:
                    inst['founded_date'] = None if emptyValue(inst['founded_date']) else datetime.fromisoformat(inst['founded_date'].replace('Z', '+00:00')).strftime("%Y-%m-%d")
                    inst['inst_type'] = InstitutionType.objects.filter(name='unknown')[0].uuid if emptyValue(inst['inst_type']) else inst['inst_type']
                    inst_add_serializer = InstCreateSerializer(data=inst)
                    inst_data_valid = inst_add_serializer.is_valid()
                    if not inst_data_valid:
                        print(inst_add_serializer.errors)
                        inst_serial_errors = handle_serializer_error(
                            errors=inst_add_serializer.errors)
                        res["code"] = 400
                        res["message"] = "参数错误：\n" + inst_serial_errors
                        return JsonResponse(res)
                    inst = inst_add_serializer.validated_data
                    inst["creator"] = u
                    inst["last_editor"] = u
                    i = inst_add_serializer.save()
                    i_uuid = i.uuid
                    institution_id_list.append(i_uuid)
                
                for dep in dep_data_list:
                    if "uuid" in dep:
                        department_id_list.append(dep['uuid'])
                    else:
                        dep['founded_date'] = None if emptyValue(dep['founded_date']) else datetime.fromisoformat(dep['founded_date'].replace('Z', '+00:00')).strftime("%Y-%m-%d")
                        dep['dep_type'] = DepartmentType.objects.filter(name='unknown')[0].uuid if emptyValue(dep['dep_type']) else dep['dep_type']
                        dep["institution"] = i_uuid
                        depart_add_serializer = DepartCreateSerializer(data=dep)
                        depart_data_valid = depart_add_serializer.is_valid()
                        if not depart_data_valid:
                            print(depart_add_serializer.errors)
                            depart_serial_errors = handle_serializer_error(
                                errors=depart_add_serializer.errors)
                            res["code"] = 400
                            res["message"] = "参数错误：\n" + depart_serial_errors
                            return JsonResponse(res)
                        depart_data = depart_add_serializer.validated_data
                        depart_data["creator"] = u
                        depart_data["last_editor"] = u
                        d = depart_add_serializer.save()
                        department_id_list.append(d.uuid)
                        
            pub_data = data
            pub_data["subjects"] = subject_id_list
            pub_data["institutions"] = institution_id_list
            pub_data["departments"] = department_id_list
            
            pub_add_serializer = PublicationCreateSerializer(data=pub_data)
            pub_data_valid = pub_add_serializer.is_valid()
            if not pub_data_valid:
                print(pub_add_serializer.errors)
                pub_serial_errors = handle_serializer_error(
                    errors=pub_add_serializer.errors)
                res["code"] = 400
                res["message"] = "参数错误：\n" + pub_serial_errors
                return JsonResponse(res)
            pub_data = pub_add_serializer.validated_data
            pub_data["creator"] = u
            pub_data["last_editor"] = u
            
            pub_data.pop('subjects', [])
            pub_data.pop('institutions', [])
            pub_data.pop('departments', [])
            
            p = None
            if publication_type == 'Journal':
                journal_data = data
                journal_data['founding_datej'] = None if emptyValue(journal_data['founding_datej']) else datetime.fromisoformat(journal_data['founding_datej'].replace('Z', '+00:00')).strftime("%Y-%m-%d")
                journal_data['publication_cycle'] = JournalPublicationCycleType.objects.filter(name='unknown')[0].uuid if emptyValue(journal_data['publication_cycle']) else journal_data['publication_cycle']
                journal_add_serializer = JournalCreateSerializer(data=journal_data)
                journal_data_valid = journal_add_serializer.is_valid()
                if not journal_data_valid:
                    print(journal_add_serializer.errors)
                    journal_serial_errors = handle_serializer_error(
                        errors=journal_add_serializer.errors)
                    res["code"] = 400
                    res["message"] = "参数错误：\n" + journal_serial_errors
                    return JsonResponse(res)
                journal_data = journal_add_serializer.validated_data
                p = Journal.objects.create(**pub_data, **journal_data)
            elif publication_type == 'Book':
                book_data = data
                book_data['publish_date'] = None if emptyValue(book_data['publish_date']) else datetime.fromisoformat(book_data['publish_date'].replace('Z', '+00:00')).strftime("%Y-%m-%d")
                book_data['language'] = Language.objects.filter(name='unknown')[0].uuid if emptyValue(book_data['language']) else book_data['language']
                
                author_id_list = []
                for author in book_data['authors']:
                    if 'uuid' in author:
                        author_id_list.append(author['uuid'])
                    else:
                        author_add_serializer = AuthorCreateSerializer(data=author)
                        author_data_valid = author_add_serializer.is_valid()
                        if not author_data_valid:
                            print(author_add_serializer.errors)
                            author_serial_errors = handle_serializer_error(
                                errors=author_add_serializer.errors)
                            res["code"] = 400
                            res["message"] = "参数错误：\n" + author_serial_errors
                            return JsonResponse(res)
                        author_data = author_add_serializer.validated_data
                        author_data["creator"] = u
                        author_data["last_editor"] = u
                        a = author_add_serializer.save()
                        author_id_list.append(a.uuid)
                        
                book_data['authors'] = author_id_list
                
                book_add_serializer = BookCreateSerializer(data=book_data)
                book_data_valid = book_add_serializer.is_valid()
                if not book_data_valid:
                    print(book_add_serializer.errors)
                    book_serial_errors = handle_serializer_error(
                        errors=book_add_serializer.errors)
                    res["code"] = 400
                    res["message"] = "参数错误：\n" + book_serial_errors
                    return JsonResponse(res)
                book_data = book_add_serializer.validated_data
                
                book_data.pop('authors', [])
                        
                p = Book.objects.create(**pub_data, **book_data)
                p.authors.set(author_id_list)
            elif publication_type == 'Conference':
                confer_data = data
                confer_data['founding_datec'] = None if emptyValue(confer_data['founding_datec']) else datetime.fromisoformat(confer_data['founding_datec'].replace('Z', '+00:00')).strftime("%Y-%m-%d")
                confer_data['meeting_cycle'] = ConferenceMeetingCycleType.objects.filter(name='unknown')[0].uuid if emptyValue(confer_data['meeting_cycle']) else confer_data['meeting_cycle']
                confer_add_serializer = ConferenceCreateSerializer(data=confer_data)
                confer_data_valid = confer_add_serializer.is_valid()
                if not confer_data_valid:
                    print(confer_add_serializer.errors)
                    confer_serial_errors = handle_serializer_error(
                        errors=confer_add_serializer.errors)
                    res["code"] = 400
                    res["message"] = "参数错误：\n" + confer_serial_errors
                    return JsonResponse(res)
                confer_data = confer_add_serializer.validated_data
                p = Conference.objects.create(**pub_data, **confer_data)
            else:
                res["code"] = 500
                res["message"] = "出版物类型不存在"
                return JsonResponse(res)
                    
            p.subjects.set(subject_id_list)
            p.institutions.set(institution_id_list)
            p.departments.set(department_id_list)
                
            res["code"] = 200
            res["message"] = "新建成功"
            res["data"] = None
        except Exception as e:
            traceback.print_exc()
            res["code"] = 500
            res["message"] = "服务器错误：" + str(e)
        return JsonResponse(res)
    
    
class PublicationInfoView(View):
    def get(self, request, id):
        res = {"code": 400, "message": "", "data": None}
        try:
            data = request.GET
            publication_type = data['type']
            target_class = getattr(Publications, publication_type)
            target = target_class.objects.get(uuid=id)
            
            p_data = PublicationInfoSerializer(target).data
            
            for inst in p_data["institutions"]:
                dep_data = inst.pop("departments", [])
                for dep in p_data["departments"]:
                    if dep["institution"] == inst:
                        dep["institution"] = inst
                inst["departments"] = dep_data
                
            if publication_type == "Journal":
                p_data.update(JournalInfoSerializer(target).data)
            elif publication_type == "Book":
                p_data.update(BookInfoSerializer(target).data)
            elif publication_type == "Conference":
                p_data.update(ConferenceInfoSerializer(target).data)
            else:
                res["code"] = 500
                res["message"] = "出版物类型不存在"
                return JsonResponse(res)
            
            res["code"] = 200
            res["message"] = "查询成功"
            res["data"] = p_data
        except Exception as e:
            traceback.print_exc()
            res["code"] = 500
            res["message"] = "服务器错误：" + str(e)
        return JsonResponse(res)
    
    def delete(self, request, id):
        res = {"code": 400, "message": "", "data": None}
        try:
            user_name = get_useraccount_from_request(request=request)
            data = json.loads(request.body)
            publication_type = data['type']
            target_class = getattr(Publications, publication_type)
            target = target_class.objects.get(uuid=id)
            if target is None:
                res["code"] = 400
                res["message"] = "该条目不存在"
                return JsonResponse(res)
            
            if len(target.literature_set.all()) > 0:
                res["code"] = 400
                res["message"] = "删除失败：该出版物仍被若干文献引用"
                return JsonResponse(res)
            
            if publication_type == 'book':
                target.authors.clear()
                
            target.subjects.clear()
            target.institutions.clear()
            target.departments.clear()
            target.delete()
            res["code"] = 200
            res["message"] = "删除成功"
            res["data"] = None
        except Exception as e:
            res["code"] = 500
            res["message"] = "服务器错误：" + str(e)
        return JsonResponse(res)
    
    def put(self, request, id):
        res = {"code": 400, "message": "", "data": None}
        try:
            user_name = get_useraccount_from_request(request=request)
            u = User.objects.filter(user_account=user_name)[0]
            data = json.loads(request.body)
            target_class = getattr(Publications, data['class_type'])
            
            subject_id_list = []
            for subject in data['subjects']:
                if 'uuid' in subject:
                    subject_id_list.append(subject['uuid'])
                else:
                    subject_add_serializer = SubjectCreateSerializer(data=subject)
                    subject_data_valid = subject_add_serializer.is_valid()
                    if not subject_data_valid:
                        print(subject_add_serializer.errors)
                        subject_serial_errors = handle_serializer_error(
                            errors=subject_add_serializer.errors)
                        res["code"] = 400
                        res["message"] = "参数错误：\n" + subject_serial_errors
                        return JsonResponse(res)
                    subject_data = subject_add_serializer.validated_data
                    subject_data["creator"] = u
                    subject_data["last_editor"] = u
                    subject_data['kt'] = KeywordType.objects.filter(name='Subject')[0]
                    t = Keyword.objects.create(**subject_data)
                    subject_id_list.append(t.uuid)
                    
            data['subjects'] = subject_id_list
            
            inst_infos = []
            for inst in data["institutions"]:
                inst_infos.append(copy.deepcopy(inst))
                if not isinstance(inst.get("departments"), list):
                    inst["departments"] = []
            
            for dep in data["departments"]:
                for i,inst in enumerate(inst_infos):
                    if dep["institution"] == inst:
                        data["institutions"][i]["departments"].append(dep)
                        
            institution_id_list = []
            department_id_list = []
            for inst in data["institutions"]:
                dep_data_list = inst.pop('departments', [])
                i_uuid = None
                if "uuid" in inst:
                    i_uuid = inst["uuid"]
                    institution_id_list.append(i_uuid)
                else:
                    inst['founded_date'] = None if emptyValue(inst['founded_date']) else datetime.fromisoformat(inst['founded_date'].replace('Z', '+00:00')).strftime("%Y-%m-%d")
                    inst['inst_type'] = InstitutionType.objects.filter(name='unknown')[0].uuid if emptyValue(inst['inst_type']) else inst['inst_type']
                    inst_add_serializer = InstCreateSerializer(data=inst)
                    inst_data_valid = inst_add_serializer.is_valid()
                    if not inst_data_valid:
                        print(inst_add_serializer.errors)
                        inst_serial_errors = handle_serializer_error(
                            errors=inst_add_serializer.errors)
                        res["code"] = 400
                        res["message"] = "参数错误：\n" + inst_serial_errors
                        return JsonResponse(res)
                    inst = inst_add_serializer.validated_data
                    inst["creator"] = u
                    inst["last_editor"] = u
                    i = inst_add_serializer.save()
                    i_uuid = i.uuid
                    institution_id_list.append(i_uuid)
                
                for dep in dep_data_list:
                    if "uuid" in dep:
                        department_id_list.append(dep['uuid'])
                    else:
                        dep['founded_date'] = None if emptyValue(dep['founded_date']) else datetime.fromisoformat(dep['founded_date'].replace('Z', '+00:00')).strftime("%Y-%m-%d")
                        dep['dep_type'] = DepartmentType.objects.filter(name='unknown')[0].uuid if emptyValue(dep['dep_type']) else dep['dep_type']
                        dep["institution"] = i_uuid
                        depart_add_serializer = DepartCreateSerializer(data=dep)
                        depart_data_valid = depart_add_serializer.is_valid()
                        if not depart_data_valid:
                            print(depart_add_serializer.errors)
                            depart_serial_errors = handle_serializer_error(
                                errors=depart_add_serializer.errors)
                            res["code"] = 400
                            res["message"] = "参数错误：\n" + depart_serial_errors
                            return JsonResponse(res)
                        depart_data = depart_add_serializer.validated_data
                        depart_data["creator"] = u
                        depart_data["last_editor"] = u
                        d = depart_add_serializer.save()
                        department_id_list.append(d.uuid)
                        
            data['institutions'] = institution_id_list
            data['departments'] = department_id_list
            
            target = target_class.objects.get(uuid=id)
            modify_serializer = PublicationCreateSerializer(instance=target, data=data)
            data_valid = modify_serializer.is_valid()
            if not data_valid:
                res["code"] = 400
                res["message"] = "参数错误：" + \
                    handle_serializer_error(
                        errors=modify_serializer.errors)
                return JsonResponse(res)
            p_data = modify_serializer.validated_data
            p_data["last_editor"] = u
            
            if data['class_type'] == 'Journal':
                journal_data = data
                journal_data['founding_datej'] = None if emptyValue(journal_data['founding_datej']) else datetime.fromisoformat(journal_data['founding_datej'].replace('Z', '+00:00')).strftime("%Y-%m-%d")
                journal_data['publication_cycle'] = JournalPublicationCycleType.objects.filter(name='unknown')[0].uuid if emptyValue(journal_data['publication_cycle']) else journal_data['publication_cycle']
                journal_add_serializer = JournalCreateSerializer(data=journal_data)
                journal_data_valid = journal_add_serializer.is_valid()
                if not journal_data_valid:
                    print(journal_add_serializer.errors)
                    journal_serial_errors = handle_serializer_error(
                        errors=journal_add_serializer.errors)
                    res["code"] = 400
                    res["message"] = "参数错误：\n" + journal_serial_errors
                    return JsonResponse(res)
                journal_data = journal_add_serializer.validated_data
                p_data.update(journal_data)
            elif data['class_type'] == 'Book':
                book_data = data
                book_data['publish_date'] = None if emptyValue(book_data['publish_date']) else datetime.fromisoformat(book_data['publish_date'].replace('Z', '+00:00')).strftime("%Y-%m-%d")
                book_data['language'] = Language.objects.filter(name='unknown')[0].uuid if emptyValue(book_data['language']) else book_data['language']
                
                author_id_list = []
                for author in book_data['authors']:
                    if 'uuid' in author:
                        author_id_list.append(author['uuid'])
                    else:
                        author_add_serializer = AuthorCreateSerializer(data=author)
                        author_data_valid = author_add_serializer.is_valid()
                        if not author_data_valid:
                            print(author_add_serializer.errors)
                            author_serial_errors = handle_serializer_error(
                                errors=author_add_serializer.errors)
                            res["code"] = 400
                            res["message"] = "参数错误：\n" + author_serial_errors
                            return JsonResponse(res)
                        author_data = author_add_serializer.validated_data
                        author_data["creator"] = u
                        author_data["last_editor"] = u
                        a = author_add_serializer.save()
                        author_id_list.append(a.uuid)
                        
                book_data['authors'] = author_id_list
                
                book_add_serializer = BookCreateSerializer(data=book_data)
                book_data_valid = book_add_serializer.is_valid()
                if not book_data_valid:
                    print(book_add_serializer.errors)
                    book_serial_errors = handle_serializer_error(
                        errors=book_add_serializer.errors)
                    res["code"] = 400
                    res["message"] = "参数错误：\n" + book_serial_errors
                    return JsonResponse(res)
                book_data = book_add_serializer.validated_data
                
                p_data.update(book_data)
            elif data['class_type'] == 'Conference':
                confer_data = data
                confer_data['founding_datec'] = None if emptyValue(confer_data['founding_datec']) else datetime.fromisoformat(confer_data['founding_datec'].replace('Z', '+00:00')).strftime("%Y-%m-%d")
                confer_data['meeting_cycle'] = ConferenceMeetingCycleType.objects.filter(name='unknown')[0].uuid if emptyValue(confer_data['meeting_cycle']) else confer_data['meeting_cycle']
                confer_add_serializer = ConferenceCreateSerializer(data=confer_data)
                confer_data_valid = confer_add_serializer.is_valid()
                if not confer_data_valid:
                    print(confer_add_serializer.errors)
                    confer_serial_errors = handle_serializer_error(
                        errors=confer_add_serializer.errors)
                    res["code"] = 400
                    res["message"] = "参数错误：\n" + confer_serial_errors
                    return JsonResponse(res)
                confer_data = confer_add_serializer.validated_data
                p_data.update(confer_data)
            else:
                res["code"] = 500
                res["message"] = "出版物类型不存在"
                return JsonResponse(res)

            subjects_data = p_data.pop('subjects', [])
            institutions_data = p_data.pop('institutions', [])
            departments_data = p_data.pop('departments', [])
            authors_data = p_data.pop("authors", [])
            
            for attr, value in p_data.items():
                setattr(target, attr, value)
            
            target.subjects.set(subjects_data)
            target.institutions.set(institutions_data)
            target.departments.set(departments_data)
            
            if data['class_type'] == 'Book':
                target.authors.set(authors_data)
            
            target.save()
            res["code"] = 200
            res["message"] = "编辑成功"
            res["data"] = None
        except Exception as e:
            res["code"] = 500
            res["message"] = "服务器错误：" + str(e)
            print(e)
        return JsonResponse(res)